//
//  PZLHTMLViewController.m
//  Various
//
//  Created by dllo on 16/3/28.
//  Copyright © 2016年 Harword. All rights reserved.
//

#import "PZLHTMLViewController.h"
#import "TFHpple.h"
#import "HLNetWorkTool.h"
#import "PZLSecondWebViewController.h"
@interface PZLHTMLViewController ()<UIWebViewDelegate>

//@property (nonatomic, strong)NSMutableArray *arr;
@property (nonatomic, strong)UIWebView *webView;
@property (nonatomic, strong)NSMutableArray *arr;

@end

@implementation PZLHTMLViewController



- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}





- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatHTML];
}


- (void)viewWillAppear:(BOOL)animated{
    // 隐藏导航栏
//    [UIView animateWithDuration:0.5 animations:^{
//        self.navigationController.navigationBar.frame = CGRectMake(0, -64, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
//    }];
    
//     self.automaticallyAdjustsScrollViewInsets = NO;
//    self.navigationController.navigationBarHidden = YES;
    // 隐藏tabbar
//    [self.tabBarController.tabBar setHidden:YES];
}


- (void)creatHTML{
    
    UIImage *image = [UIImage imageNamed:@"tqt_l_button"];
    // 取消渲染效果
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(goToBack)];
    self.navigationItem.leftBarButtonItem = leftBarButton;

    
    
    if (self.full_url != nil) {
        
        self.navigationItem.title = nil;
        self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64*sHEIGHT, sWEIGHT*414, sHEIGHT*736+100*sHEIGHT)];
        self.webView.backgroundColor = [UIColor whiteColor];
        self.webView.delegate = self;
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(100*sHEIGHT, 0, 0, 0);
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, sWEIGHT*414, -164*sHEIGHT)];
        view1.backgroundColor = [UIColor colorWithRed:70/255.0 green:209/255.0 blue:245/255.0 alpha:1];
        [self.webView.scrollView addSubview:view1];
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15*sWEIGHT, -140*sHEIGHT, sWEIGHT*414 - 30*sWEIGHT, 100*sHEIGHT)];
        label.text = self.title;
        label.font = [UIFont fontWithName:@"Arial-BoldItalicMT" size:30*sWEIGHT];
        label.textColor = [UIColor whiteColor];
        label.numberOfLines = 0;
        [label sizeToFit];
        
        
        UILabel *labelAuther = [[UILabel alloc] initWithFrame:CGRectMake(15*sWEIGHT, -45*sHEIGHT, sWEIGHT*150, 30*sHEIGHT)];
        labelAuther.text = self.auther;
        labelAuther.font = [UIFont fontWithName:@"Arial" size:20*sWEIGHT];
        labelAuther.textColor = [UIColor whiteColor];
        [view1 addSubview:label];
        [view1 addSubview:labelAuther];
     
    
        self.webView.scrollView.bounces = NO;
        [self.view addSubview:self.webView];
        [self creatNet];
    }

    
    if (self.web_url != nil) {
        
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, sWEIGHT*414, sHEIGHT*736)];
        webView.backgroundColor = [UIColor whiteColor];
        webView.delegate = self;
        
        NSString *path = self.web_url;
        NSURL *url = [NSURL URLWithString:path];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        webView.scalesPageToFit = YES;// 大小根据屏幕大小自动缩放
        webView.opaque = NO;// 不设置这个值页面始终是白色;
        
        [webView loadRequest:request];
        [self.view addSubview:webView];
        
      

    }
    
    
    
 
    
    /**
     *  把网页转为HTML铺在webview上
     */
    /*
    NSString *stringUrl = self.web_url;
    NSData *htmlData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:stringUrl]];
    NSString *strWeb = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
    [webView loadHTMLString:strWeb baseURL:nil];
    */
    
    
    
}

   - (void)goToBack{
       [self.navigationController popToRootViewControllerAnimated:YES];
    }

#pragma mark - 另一种方法:需要签webView协议
#if 1
- (void)creatNet{
    [HLNetWorkTool getWithURL:self.full_url Parameter:nil HttpHeader:nil ResponseType:ResponseTypeJSON Progress:^(NSProgress *progress) {
        
        
    } Success:^(id result) {
//        NSMutableArray *arr = [NSMutableArray array];
        NSDictionary *dicData = [result objectForKey:@"data"];
        NSString *str = [dicData objectForKey:@"content"];
        self.arr = [NSMutableArray arrayWithArray:[dicData objectForKey:@"media"]];
        
//        NSLog(@"%@", arr);
#pragma mark - 使用TFHpple替换显示图片
        
        //        NSString *urlString = @"http://cnblogs.com/YouXianMing/";
        //        NSData *htmlData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]];
        
        
        NSData *htmlData = [str dataUsingEncoding:NSUTF8StringEncoding];
        // 解析html数据
        TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
        // 根据标签来进行过滤
        NSArray *dataArray = [xpathParser searchWithXPathQuery:@"//img"];
        // 开始整理数据
        NSInteger i = 0;
        for (TFHppleElement *hppleElement in dataArray) {
            
            // 返回特定字符串的位置
            NSRange range = [str rangeOfString:[hppleElement.attributes objectForKey:@"src"]];

            str =  [str stringByReplacingCharactersInRange:range withString:[self.arr[i++] objectForKey:@"raw_url"]];
            NSLog(@"%lu", range.location);


            str =  [str stringByReplacingCharactersInRange:range withString:[_arr[i++] objectForKey:@"raw_url"]];
//            NSLog(@"%lu", range.location);

            


        }
//        sleep(5);
        [self.webView loadHTMLString:str baseURL:nil];
        
        
    } Failure:^(NSError *error) {
        
        
    }];
    
}
#endif




#pragma mark - 另一种方法:需要签webView协议

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (self.arr) {
        //        [webView stringByEvaluatingJavaScriptFromString:@"alert('测试一个alert')"];
        for (NSInteger i = 0; i < self.arr.count; i++) {
            NSString *imageUrl = self.arr[i][@"raw_url"];





#pragma mark - 替换图片网址可代替上面的TFHpple
#if 0
            NSString *str = [NSString stringWithFormat:@"var img=document.getElementById('id_image_%ld'); img.src='%@';", i, imageUrl];
#endif
            
            
            
            NSString *str = [NSString stringWithFormat:@"var div = document.getElementById('id_imagebox_%ld');div.onclick='';", i];
            NSLog(@"%@----%@", str, imageUrl);


//            NSString *str = [NSString stringWithFormat:@"var aimg=document.getElementById('id_image_%ld'); aimg.src=\"%@\"", i, imageUrl];
//            NSLog(@"%@----%@", str, imageUrl);



            [webView stringByEvaluatingJavaScriptFromString:str];
        }
        
    }
    if (self.full_url != nil) {
        webView.frame = CGRectMake(0, 64, sWEIGHT*414, sHEIGHT*736-64*sHEIGHT);
    }
    

    
}





// 去看看
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
 
        if (navigationType == UIWebViewNavigationTypeLinkClicked) {
            NSString *str = request.URL.absoluteString;
            str = [str stringByRemovingPercentEncoding];
        
            
            
            NSRange range = [str rangeOfString:@"content_url"];
            NSRange range2 = NSMakeRange(0, 0);
            
            // 判断是否含有order_url
            if ([str rangeOfString:@"order_url"].location != NSNotFound) {
                range2 = [str rangeOfString:@"order_url"];
            }else{
                range2 = [str rangeOfString:@"share_url"];
            }
            
            str = [str substringToIndex:range2.location];
            NSLog(@"****%@", str);
            
            str = [str substringFromIndex:range.location];
            NSRange range3 = [str rangeOfString:@"http"];
            str = [str substringFromIndex:range3.location];
        
            str = [str stringByReplacingOccurrencesOfString:@"\\" withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"," withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"\"\"" withString:@""];
        
            PZLSecondWebViewController *secondWebVC = [[PZLSecondWebViewController alloc]init];
            secondWebVC.temp = str;
            [self.navigationController pushViewController:secondWebVC animated:YES];

            
        }
            return YES;

    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}



@end
